<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useUserStore } from '../../store/user'
import { Loading } from '@nutui/icons-vue-taro'

const userStore = useUserStore()

// 佣金数据
let commissionData = $ref({
  total: 0,
  available: 0,
  frozen: 0
})

// 团队数据
let teamData = $ref({
  directMembers: 0,
  totalMembers: 0,
  teamList: [] as any[]
})

// 获取分销数据
const getDistributionData = async () => {
  try {
    const res = await userStore.getDistributionData()
    commissionData = res.commission
    teamData = res.team
  } catch (error) {
    console.error('获取分销数据失败:', error)
  }
}

// 生成推广二维码
const qrVisible = ref(false)
const qrLoading = ref(false)
const qrUrl = ref('')

// 生成二维码
const generateQRCode = async () => {
  try {
    qrLoading.value = true
    const url = await userStore.generateQRCode()
    
    // 创建canvas上下文
    const ctx = uni.createCanvasContext('qrcodeCanvas', this)
    
    // 绘制二维码
    ctx.drawImage(url, 0, 0, 200, 200)
    ctx.draw(() => {
      qrUrl.value = url
      qrVisible.value = true
    })
  } catch (error) {
    uni.showToast({ title: '二维码生成失败', icon: 'none' })
  } finally {
    qrLoading.value = false
  }
}

// 保存到相册
const saveQRCode = () => {
  uni.saveImageToPhotosAlbum({
    filePath: qrUrl.value,
    success: () => uni.showToast({ title: '保存成功' }),
    fail: () => uni.showToast({ title: '保存失败请重试', icon: 'none' })
  })
}

onMounted(() => {
  getDistributionData()
})
</script>

<template>
  <view class="distribution-container">
    <!-- 佣金概览 -->
    <view class="commission-card">
      <view class="total-commission">
        <text class="label">累计佣金</text>
        <text class="value">¥{{ commissionData.total }}</text>
      </view>
      <view class="commission-detail">
        <view class="detail-item">
          <text>可提现</text>
          <text>¥{{ commissionData.available }}</text>
        </view>
        <view class="detail-item">
          <text>冻结中</text>
          <text>¥{{ commissionData.frozen }}</text>
        </view>
      </view>
    </view>

    <!-- 推广入口 -->
    <view class="promotion-section">
      <nut-button 
        type="primary" 
        block
        :loading="qrLoading"
        @click="generateQRCode"
      >
        生成推广二维码
      </nut-button>

      <!-- 二维码弹窗 -->
      <nut-popup
        v-model:visible="qrVisible"
        position="center"
        round
      >
        <view class="qr-code-box">
          <canvas 
            canvas-id="qrcodeCanvas"
            class="qrcode-canvas"
          />
          <view class="qr-actions">
            <nut-button
              type="default"
              @click="qrVisible = false"
            >
              关闭
            </nut-button>
            <nut-button
              type="primary"
              @click="saveQRCode"
            >
              保存到相册
            </nut-button>
          </view>
        </view>
      </nut-popup>

      <!-- 加载状态 -->
      <nut-overlay v-model:visible="qrLoading">
        <view class="loading-wrapper">
          <Loading />
          <text>二维码生成中...</text>
        </view>
      </nut-overlay>
      <button class="qr-btn" @tap="generateQRCode">
        <image src="../../assets/icons/qr-code.svg" />
        <text>推广二维码</text>
      </button>
    </view>

    <!-- 团队管理 -->
    <view class="team-section">
      <view class="team-header">
        <text>我的团队</text>
        <text>共{{ teamData.totalMembers }}人</text>
      </view>
      <view class="team-list">
        <view v-for="(member, index) in teamData.teamList" :key="index" class="team-item">
          <image :src="member.avatar" class="avatar" />
          <text class="name">{{ member.name }}</text>
          <text class="time">{{ member.joinTime }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.distribution-container {
  padding: 20rpx;
}

.commission-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);

  .total-commission {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .label {
      font-size: 28rpx;
      color: #666;
    }

    .value {
      font-size: 40rpx;
      font-weight: bold;
      color: #e93b3d;
    }
  }

  .commission-detail {
    display: flex;
    justify-content: space-between;

    .detail-item {
      display: flex;
      flex-direction: column;
      align-items: center;

      text:first-child {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 10rpx;
      }

      text:last-child {
        font-size: 32rpx;
        color: #333;
      }
    }
  }
}

.promotion-section {
  margin: 30rpx 0;

  .qr-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff;
    height: 100rpx;
    border-radius: 16rpx;

    image {
      width: 40rpx;
      height: 40rpx;
      margin-right: 15rpx;
    }
  }
}

.team-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;

  .team-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30rpx;

    text:first-child {
      font-size: 32rpx;
      font-weight: bold;
    }

    text:last-child {
      font-size: 28rpx;
      color: #666;
    }
  }

  .team-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #eee;

    .avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      margin-right: 20rpx;
    }

    .name {
      flex: 1;
      font-size: 28rpx;
    }

    .time {
      font-size: 24rpx;
      color: #999;
    }
  }
}
</style>